<?php
/**
 * Created by PhpStorm.
 * User: Zhoujinda
 * Date: 2016/6/7
 * Time: 17:14
 */
namespace Mengwu\Controller;

use Admin\Api\OrdersPaycodeApi;
use Mengwu\Api\MwApi;
use Mengwu\Api\Pay\Alipaydirect;
use Shop\Api\WalletApi;

class OrderController extends BaseStoreController{

    public function confirm(){
        if(IS_POST){
            $this->assignTitle('确认订单');
            $url = urlencode($_SERVER['HTTP_REFERER']);
            if(empty($this->userinfo)) redirect(U('mengwu/account/login').'?redirect='.$url);
            $this->noCachePage();

            if(!$this->isLogin()){
                exit('未登录');
            }
            $from = I('from');

            //查询钱包
            $result = apiCall(WalletApi::GET_INFO_If_NOT_EXIST_THEN_ADD,[$this->getUID()]);
            if($result['status']){
                $this->assign('wallet',$result['info']['account_balance']);
            }else{
                exit('数据错误04');
            }

            if($from=='spcart'){
                //来自购物车
                $cart_ids = I('cart_ids');
                $cart_ids = explode(',',$cart_ids);
                $cart_info = [];
                $store_info = [];

                foreach($cart_ids as $val){
                    $result = mwApi(MwApi::BY_ShoppingCart_getInfo,['api_ver'=>101,'id'=>$val]);
                    if($result['status']){
                        if(empty($store_info)){
                            $store_info = $result['info'];
                            unset($store_info['carts']);
                        }
                        $cart_info[] = $result['info']['carts'];
                    }
                }

                if(count($cart_info)==0){
                    exit('数据错误01!');
                }

                $PICTURE_REMOTE_URL = C('PICTURE_REMOTE_URL');
                foreach($cart_info as &$val){
                    $val['icon_url'] = $PICTURE_REMOTE_URL.$val['icon_url'].'&size=80';
                }

                $order_info = [
                    'from' => $from,
                    'store_info' => $store_info,
                    'order_items' => $cart_info
                ];

                $this->assign('order_info', json_encode($order_info));

                $this->boye_display();
                return;
            }
            if($from=='buy'){
                //来自立即购买
                $buy_info = [
                    'pid' => I('pid'),
                    'count' => I('count'),
                    'psku_id' => I('psku_id'),
                    'group_id' => I('group_id')
                ];
                //查询商品信息
                $data = [
                    'pid' => $buy_info['pid'],
                    'uid' => $this->getUID(),
                    'gid' => $buy_info['group_id']
                ];
                $result = mwApi(MwApi::BY_Product_detail,$data);

                if(!$result['status']){
                    exit('数据错误02');
                }
                $info = $result['info'];
                $sku_info = [];
                if($info['has_sku']){
                    //多规格
                    foreach($info['sku_list'] as $val){
                        if($val['id']==$buy_info['psku_id']){
                            $sku_info = $val;
                            break;
                        }
                    }
                }else{
                    //单规格
                    $sku_info = $info['sku_info'];
                }

                $PICTURE_REMOTE_URL = C('PICTURE_REMOTE_URL');
                $store_info = $info['store_benefit'];
                $order_items = [
                    'id' => 0,
                    'uid' => $this->getUID(),
                    'p_id' => $info['id'],
                    'sku_id' => $sku_info['sku_id'],
                    'sku_desc' => $sku_info['sku_desc'],
                    'icon_url' => $PICTURE_REMOTE_URL.$info['main_img'].'&size=80',
                    'count' => $buy_info['count'],
                    'name' => $info['name'],
                    'ori_price' => $sku_info['ori_price'],
                    'price' => $sku_info['price'] //默认sku价格

                ];

                //判断是否用会员价  会员价优先于sku价
                $member_price = $sku_info['member_price'];
                if(!empty($member_price) && floatval($member_price)>0) $order_items['price'] = $member_price;

                //判断是否参与分组  分组价优先于会员价
                foreach($info['group_info'] as $val){
                    if($val['gid']==$buy_info['group_id']){

                        foreach($val['sku_info'] as $val2){
                            if($val2['sku_id']==$buy_info['psku_id']){
                                //判断是否在期限内
                                $time = time();
                                if($val2['start_time']<=$time && $time<=$val2['end_time']){
                                    //在期限内使用分组价格
                                    $order_items['price'] = $val2['price'];
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }

                $order_info = [
                    'from' => $from,
                    'buy_info' => $buy_info,
                    'store_info' => $store_info,
                    'order_items' => [$order_items]
                ];

                $this->assign('order_info', json_encode($order_info));

                $this->boye_display();
                return;
            }
            exit('参数错误03');

        }
//        else{
//            $cart_info = [];
//            $this->assign('order_items', json_encode($cart_info));
//            $this->boye_display();
//        }
    }

    /**
     * 生成订单
     */
    public function order_add(){
        if(IS_POST){
            $this->needLogin();
            
            $note = I('note',[]);
            $address_id = I('address_id');
            $coupon_id = I('coupon_id');
            $red_id = I('red_id');
            $money = I('money');
            $order_info = htmlspecialchars_decode(I('data'));
            $order_info = json_decode($order_info,true);
            $order_items = $order_info['order_items'];

            if($order_info['from']=='spcart'){
                $cart_ids = [];
                foreach($order_items as $val){
                    $cart_ids[] = $val['id'];
                }
                $cart_ids = implode('-',$cart_ids);

                $data = [
                    'api_ver' => 101,
                    'uid' => $this->getUID(),
                    'cart_ids' => $cart_ids,
                    'red_ids' => $red_id,
                    'coupon_ids' => $coupon_id,
                    'money' => $money,
                    'notes' => $note,
                    'address_id' =>$address_id,
                    'from' => 1
                ];

                $result = mwApi(MwApi::BY_Orders_add,$data);

                $this->apiReturn($result,null);
                return;
            }
            if($order_info['from']=='buy'){
                $buy_info = $order_info['buy_info'];
                $item_info = $order_items[0];
                $pid = $item_info['p_id'];
                $psku_id = $buy_info['psku_id'];
                $group_id = $buy_info['group_id'];
                $count = $item_info['count'];
                $data = [
                    'uid' => $this->getUID(),
                    'pid' => $pid,
                    'psku_id' => $psku_id,
                    'count' => $count,
                    'address_id' => $address_id,
                    'red_id' => $red_id,
                    'coupon_id' => $coupon_id,
                    'money' => $money,
                    'note' => $note,
                    'from' => 1,
                    'group_id' => $group_id,
                    'package_id' => ''
                ];

                $result = mwApi(MwApi::BY_Orders_addBySku,$data);
                $this->apiReturn($result,null);
                return;
            }
            exit('参数错误01');
        }
    }

    /**
     * 跳转支付
     */
    public function jump2Pay(){
        if(IS_POST){
            $this->jump2login();

            $pay_info = json_decode(htmlspecialchars_decode(I('pay_info')),true);;
            $pay_type = I('pay_type');

            //验证订单
            $name = $pay_info['name'];
            $desc = $pay_info['desc'];
            $code = $pay_info['code'];
            $total_price = $pay_info['total_price'];
            $key = $pay_info['key'];

            $encode = urlencode($code.$name.$desc.$total_price);
            $encode = md5(strtolower($encode));
            $str = pay_encrypt_md5($encode);

            if($str != $key){
                exit('订单存在问题，无法支付!');
            }
            if($total_price<=0) $total_price = 0.01;
            $total_price = 0.01;
            switch($pay_type){
                case 0:
                    //支付宝
                    $pay = new Alipaydirect();
                    $pay->create_direct_pay_by_user($code,$name,$total_price);
                    return;
                case 1:
                    //微信
                    exit('INVALID TYPE');
                case 2:
                    //财付通
                    exit('INVALID TYPE');
            }
        }
    }

    /**
     * 重新支付
     */
    public function pay(){

        $this->jump2login();

        $this->assignTitle('订单重新支付');

        $oid = I('id');
        if(empty($oid))$this->errorPage('订单错误');

        $isPayOver = $this->isPayOver($oid);
        if($isPayOver){
            $this->errorPage('订单已支付!');
        }

        $data = [
            'uid' => $this->getUID(),
            'oid' => I('id')
        ];

        $result = mwApi(MwApi::BY_Orders_pay,$data);

        if(!$result['status']){
            exit($result['info']);
        }
        $pay_info = $result['info'];
        $this->assign('pay_info', json_encode($pay_info));

        //查询钱包
        $result = apiCall(WalletApi::GET_INFO_If_NOT_EXIST_THEN_ADD,[$this->getUID()]);
        if($result['status']){
            $this->assign('wallet',$result['info']['account_balance']);
        }else{
            exit('error');
        }


        $this->boye_display();

    }

    /**
     * 支付成功页面
     */
    public function pay_success(){
        $this->assignTitle('支付成功');
        $this->boye_display();
    }

    /**
     * 判断订单是否已支付 根据订单ID code
     */
    private function isPayOver($oid=false,$order_code=false){
        if(!$oid && !$order_code)return false;
        $data = [];
        if($oid) $data['oid'] = $oid;
        if($order_code) $data['order_code'] = $order_code;
        $result = mwApi(MwApi::BY_Orders_detail,$data);

        if($result['status']){
            $pay_status = $result['info']['pay_status'];
            if($pay_status==1 || $pay_status==2){
                //已付款
                return true;
            }else{
                return false;
            }

        }else{
            return false;
        }
    }
    
    /**
     * 返回订单是否支付完成 根据out_trade_nos
     */
    public function payStatus(){
        if(IS_POST){
            $out_trade_nos = I('code');
            if(empty('code'))$this->ajaxReturnErr('error');
            $p_pos = strpos($out_trade_nos,"P");
            $pay_id = substr($out_trade_nos,$p_pos+1,strlen($out_trade_nos)-$p_pos);

            $map=array(
                'id'=>$pay_id
            );
            $result = apiCall(OrdersPaycodeApi::GET_INFO,array($map));

            if($result['status'] && is_array($result['info'])){
                if($result['info']['pay_status']==1){
                    //已成功
                    $this->ajaxReturnSuc('success');
                }else{
                    //未支付
                    $this->ajaxReturnErr('false');
                }
            }
            $this->ajaxReturnErr('error');
        }
    }
    

}